<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>在线客服</title>
    <style>
        .message {
            height: 500px;
            border: 1px solid #dddd;
            width: 65%;
            margin-left: 15%;
        }
        .message-box {
            border: 1px solid black;
            background-color:#cccccc;
        }  
        #txt {
            width: 50%;
            height: 50px;
            margin-left: 15%;
        }

    </style>
</head>
<body>
{% for id in user %}
{% if id == 1%}
<h2 style="margin-left: 45%">{{ username }}</h2>
{% else %}
<h2 style="margin-left: 35%">新能源汽车官方4s店</h2>
{% endif %}
{% endfor %}
<ul class="message" id="message" style="overflow-y: auto"></ul>
<div>
    <input type="text" placeholder="请输入" id="txt">
    <input type="button" value="发送" onclick="sendMessage()" style="width: 20%;height: 55px">
    <input type="button" value="关闭" onclick="closeCount()">
</div>
</body>
<script>
    //创建连接
    socket = new WebSocket("ws://127.0.0.1:8000/chat/{{ group }}/");

    //创建好连接之后自动触发(服务端执行self.accept())
    socket.onopen = function (event){
        let tag= document.createElement("div")
        tag.innerText = "状态：[在线]";
        document.getElementById("message").appendChild(tag);
    }

    //当websocket接收到服务端发来的消息时，自动触发这个函数
    socket.onmessage = function (event){
        user = {{ user}}
        console.log(event.data)
        let tag= document.createElement("div")
          // 获取当前时间并格式化为字符串
        let now = new Date();
        let datePart = now.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
        });

        // 格式化时间部分
        let timePart = now.toLocaleTimeString('zh-CN', {
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false // 如果需要24小时制，请设置此选项为false
        });

        // 组合日期和时间
        let timestamp = `${datePart} ${timePart}`;
        tag.innerText =timestamp +'\n'+ event.data ;
        tag.classList.add("message-box");
        document.getElementById("message").appendChild(tag);
    }

    function sendMessage(){
        let tag=document.getElementById("txt");
        user = {{ user }}
        if(user === 0)
        {socket.send("客服 \t: {{ timestamp }}" + tag.value);}
        else
        {socket.send("{{ username }}\t:" + tag.value);}
    }

    function closeCount(){
        socket.close()//关闭
    }
</script>
</html>